import React, { Component, ReactNode } from 'react';
import { withTranslation, WithTranslation } from 'react-i18next';

interface Props extends WithTranslation {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
  errorInfo?: string;
}

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error): State {
    // 更新state以便下一次渲染能够显示降级后的UI
    return { 
      hasError: true,
      error
    };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // 记录错误信息
    console.error('ErrorBoundary caught an error:', error, errorInfo);
    
    this.setState({
      error,
      errorInfo: errorInfo.componentStack || undefined
    });

    // 这里可以将错误信息发送到错误报告服务
    // 例如：reportErrorToService(error, errorInfo);
  }

  handleClearCacheAndRefresh = () => {
    try {
      // 清除可能的问题状态
      sessionStorage.removeItem('appInitialized');
      sessionStorage.removeItem('app_refresh_lock');
      sessionStorage.removeItem('app_refresh_attempts');
      sessionStorage.removeItem('app_startup_timeout');
      
      // 保存关键数据
      const userData = localStorage.getItem('userData');
      const appVersion = localStorage.getItem('app_cache_version');
      
      // 清空localStorage
      localStorage.clear();
      
      // 恢复关键数据
      if (userData) {
        localStorage.setItem('userData', userData);
      }
      if (appVersion) {
        localStorage.setItem('app_cache_version', appVersion);
      }
      
      // 清除sessionStorage
      sessionStorage.clear();
      
      // 重新加载页面
      window.location.reload();
    } catch (error) {
      // console.error('清除缓存失败:', error);
      console.error('clear cache failed',error);
      // 如果清除缓存失败，直接重新加载
      window.location.reload();
    }
  };

  render() {
    const { t } = this.props;
    
    if (this.state.hasError) {
      // 如果提供了自定义fallback，使用它
      if (this.props.fallback) {
        return this.props.fallback;
      }

      // 默认的错误UI
      return (
        <div style={{
          padding: '20px',
          textAlign: 'center',
          backgroundColor: '#1a1a1a',
          color: '#ffffff',
          minHeight: '100vh',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
        }}>
          <div style={{
            maxWidth: '600px',
            width: '100%',
            padding: '40px',
            backgroundColor: '#2a2a2a',
            borderRadius: '12px',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)'
          }}>
            <h1 style={{
              fontSize: '24px',
              marginBottom: '16px',
              color: '#ff6b6b'
            }}>
              😓 {t('errorBoundary.title')}
            </h1>
            
            <p style={{
              fontSize: '16px',
              lineHeight: '1.5',
              marginBottom: '24px',
              color: '#cccccc'
            }}>
              {t('errorBoundary.description')}
            </p>

            <div style={{
              display: 'flex',
              justifyContent: 'center',
              marginBottom: '24px'
            }}>
              <button
                onClick={this.handleClearCacheAndRefresh}
                style={{
                  padding: '12px 24px',
                  backgroundColor: '#FF9800',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontSize: '14px',
                  fontWeight: '500',
                  transition: 'background-color 0.2s'
                }}
                onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#F57C00'}
                onMouseOut={(e) => e.currentTarget.style.backgroundColor = '#FF9800'}
              >
                🔄 {t('errorBoundary.clearCacheAndRefresh')}
              </button>
            </div>

            {/* 开发环境下显示详细错误信息 */}
            {import.meta.env.DEV && this.state.error && (
              <details style={{
                backgroundColor: '#333',
                padding: '16px',
                borderRadius: '6px',
                marginTop: '16px',
                textAlign: 'left'
              }}>
                <summary style={{
                  cursor: 'pointer',
                  fontSize: '14px',
                  fontWeight: '500',
                  marginBottom: '8px'
                }}>
                  🔍 {t('errorBoundary.viewErrorDetails')}
                </summary>
                <pre style={{
                  fontSize: '12px',
                  lineHeight: '1.4',
                  overflow: 'auto',
                  maxHeight: '200px',
                  color: '#ff6b6b',
                  margin: '8px 0 0 0'
                }}>
                  {this.state.error.toString()}
                  {this.state.errorInfo && `\n\n${this.state.errorInfo}`}
                </pre>
              </details>
            )}

            <p style={{
              fontSize: '12px',
              color: '#888',
              marginTop: '20px',
              lineHeight: '1.4'
            }}>
              {t('errorBoundary.persistentProblem')}
            </p>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

export default withTranslation()(ErrorBoundary); 